package com.cssy.xxkj.logic.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.contants.BillTypeConstant;
import com.cssy.xxkj.logic.dao.LogicProdDispatchingDetailDAO;
import com.cssy.xxkj.logic.dao.LogicProdDispatchingDetailItemDAO;
import com.cssy.xxkj.logic.dao.LogicProductionDailyDAO;
import com.cssy.xxkj.logic.dao.LogicProductionDailyItemDAO;
import com.cssy.xxkj.logic.dao.SystemLogDAO;
import com.cssy.xxkj.logic.entity.LogicProductionDailyDO;
import com.cssy.xxkj.logic.entity.LogicProductionDailyItemDO;
import com.cssy.xxkj.logic.entity.LogicProductionDispatchingDetailDO;
import com.cssy.xxkj.logic.entity.LogicProductionDispatchingDetailItemDO;
import com.cssy.xxkj.logic.service.ILogicProductionDailyService;
import com.cssy.xxkj.logic.util.ArrayUtils;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.impl.SyCodeService;
/**
 * 生产日报业务方法
 * @modify hf 
 *
 */
@Service("logicProductionDailyService")
public class LogicProductionDailyServiceImpl implements ILogicProductionDailyService {
	
	private static final Logger logger = Logger.getLogger(LogicProductionDailyServiceImpl.class);
	
	//生产日报
	@Resource(name = "logicProductionDailyDAO")
	private LogicProductionDailyDAO logicProductionDailyDAO;
	//生产日报item
	@Resource(name = "logicProductionDailyItemDAO")
	private LogicProductionDailyItemDAO  logicProductionDailyItemDAO;
	//生产派工详情
	@Resource(name = "logicProdDispatchingDetailDAO")
	private LogicProdDispatchingDetailDAO logicProdDispatchingDetailDAO;
	//生产派工详情item
	@Resource(name = "logicProdDispatchingDetailItemDAO")
	private LogicProdDispatchingDetailItemDAO logicProdDispatchingDetailItemDAO;
	
	@Resource(name = "systemLogDAO")
	private SystemLogDAO systemLogDAO;
	
	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;
	
	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs=new SearchResult(scs);
		List<LogicProductionDailyDO>  list=logicProductionDailyDAO.find(scs);
		rs.setRecordCount(logicProductionDailyDAO.count(scs));
		rs.setResults(list);
		return rs;
	}
	
	@Override
	public SearchResult findListByRoleExample(SearchConditions scs)
			throws SyBaseException{
		SearchResult rs=new SearchResult(scs);
		List<LogicProductionDailyDO> list = logicProductionDailyDAO.findByRole(scs);
		rs.setRecordCount(logicProductionDailyDAO.countByRole(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		logicProductionDailyDAO.deleteLogicProductionDailyDOByPrimaryKey(id);
		return null;
	}

	@Override
	public Integer update(LogicProductionDailyDO t, User user) throws SyBaseException {
		t.setBizModifyName(user.getName());
		t.setBizModifyDate(new Date());
		t.setBizVersionMark(t.getBizVersion());
		t.setBizVersion(t.getBizVersion()+1);
		return logicProductionDailyDAO.updateLogicProductionDailyDO(t);
	}

	@Override
	public LogicProductionDailyDO save(LogicProductionDailyDO sodo, User user) throws SyBaseException {
		sodo.setBizCreatorName(user.getName());
		sodo.setBizCreatorDate(new Date());
		sodo.setBizVersion(1);
		logicProductionDailyDAO.insertLogicProductionDailyDO(sodo);
		return sodo;
	}

	@Override
	public LogicProductionDailyDO findListById(String id) throws SyBaseException {
		return logicProductionDailyDAO.findLogicProductionDailyDOByPrimaryKey(id);
	}


	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		return logicProductionDailyDAO.deleteBizRemoved(id);
	}

	

	@Override
	public List<LogicProductionDailyItemDO> findDispatItemList(String id) throws SyBaseException {
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);
		scs.addCondition("zd001ProDailyId", id, SearchCondition.OP_EQUAL);
		List<LogicProductionDailyItemDO>  list=logicProductionDailyItemDAO.find(scs);
		return list;
	}

	@Override
	public void dailySave(HttpServletRequest request, LogicProductionDailyDO curAP)
			throws SyBaseException {
		try {
			//物料
			String itemdata = request.getParameter("itemdata");
			String paramflag =request.getParameter("paramflag");
			curAP.setZd008Billstatus(paramflag);//单据状态
			List<LogicProductionDailyItemDO> itemlist = JSONArray.parseArray(itemdata,LogicProductionDailyItemDO.class);
			User user = SessionUtil.getUser(request);
			//原始单据id
			String detailId = curAP.getZd002OriId();
			if(curAP==null||StringUtils.isBlank(curAP.getId())){
				//新增
				SearchConditions dailyScs = new SearchConditions();
				dailyScs.addCondition("zd002OriId", detailId, SearchCondition.OP_EQUAL);
				dailyScs.addCondition("zd008Billstatus", BillStatusUtil.PRODAILY_BILL_STATUS_ONEW, SearchCondition.OP_EQUAL);
				Integer dailyCount = this.logicProductionDailyDAO.count(dailyScs);
				if(dailyCount!=null &&dailyCount>0){
					throw new SyBaseException(curAP.getZd002OriCode()+"料单号存在未处理的日报");
				}
				
				String id = IDCodeTypeUtil.getId();
				curAP.setId(id);
				String formCode = syCodeService.getCode(BillTypeConstant.PRODAILY,BillTypeConstant.PRODAILY,SyCode.DATE_YYMM,5);
				curAP.setZd001FormCode(formCode);
				this.save(curAP,user);
				for (LogicProductionDailyItemDO item : itemlist) {
					item.setZd001ProDailyId(id);
					item.setZd002ProDailyCode(formCode);
					item.setId(IDCodeTypeUtil.getId());
					logicProductionDailyItemDAO.insertLogicProductionDailyItemDO(item);
				}
				logger.info("新增生产日报成功");
			}else{
				//修改
				int rowUp = this.update(curAP, user);
				if(rowUp==0){
					throw new SyBaseException("您操作的单据数据发生了改变!请您重新打开编辑！");
				}
				
				for(LogicProductionDailyItemDO dailyItem : itemlist){
					if(dailyItem==null){
						continue;
					}
					dailyItem.setZd001ProDailyId(curAP.getId());
					dailyItem.setZd002ProDailyCode(curAP.getZd001FormCode());
					if(StringUtils.isBlank(dailyItem.getId())){
						dailyItem.setId(IDCodeTypeUtil.getId());
						logicProductionDailyItemDAO.insertLogicProductionDailyItemDO(dailyItem);
					}else{
						logicProductionDailyItemDAO.updateLogicProductionDailyItemDO(dailyItem);
					}
				}
			}
			
			//是否提交
			if(BillStatusUtil.PRODAILY_BILL_STATUS_TWO.equals(curAP.getZd008Billstatus())){
				LogicProductionDispatchingDetailDO detail = logicProdDispatchingDetailDAO
									.findLogicProductionDispatchingDetailDOByPrimaryKey(detailId);
				if(detail==null){
					throw new SyBaseException("您操作的原始单据数据发生了改变!请您重新打开编辑！");
				}
				detail.setZd008WorkStatus(BillStatusUtil.PRODISPATDTL_BILL_STATUS_ZONE);
				detail.setZd008WorkDate(new Date());
				detail.setBizVersionMark(detail.getBizVersion());
				detail.setBizVersion(detail.getBizVersion()+1);
				detail.setZd008WorkDate(new Date());
				int detailUp = logicProdDispatchingDetailDAO.updateLogicProductionDispatchingDetailDO(detail);
				if(detailUp==0){
					throw new SyBaseException("您操作的原始单据数据发生了改变!请您重新打开编辑！");
				}
				logger.info("更新生产派工单状态成功");
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error("操作生产日报失败！");
			throw new SyBaseException(GlobalResLoader.getOpfailed()+ e.getMessage());
		}
	}
	
	/**
	 * 批量保存日报
	 */
	@Override
	public void pldailyToSave(HttpServletRequest request, List<String> detailIdList, String flagMark)
			throws SyBaseException{
		try{
			if(detailIdList==null||detailIdList.isEmpty()||detailIdList.size()==0){
				return;
			}else{
				Map<LogicProductionDispatchingDetailDO,List> detailMap = new HashMap<LogicProductionDispatchingDetailDO, List>();
				//分批次查询
				List<List<String>> tailIdListToList = ArrayUtils.splitToFixedList(detailIdList, 100, false);
				for(List<String> _tailIdList :tailIdListToList){
					for(String tailId : _tailIdList){
						Map<String, Object> paramMap = new HashMap<String, Object>();
						paramMap.put("detailId", tailId);
						LogicProductionDispatchingDetailDO detailEntity = logicProdDispatchingDetailDAO.findLogicProductionDispatchingDetailDOByPrimaryKey(tailId);
						List<LogicProductionDispatchingDetailItemDO> detailItems = logicProdDispatchingDetailItemDAO.findListByMap(paramMap);
						detailMap.put(detailEntity, detailItems);
					}
				}
				
				for(LogicProductionDispatchingDetailDO detailEntity : detailMap.keySet()){
					if(detailEntity==null||StringUtils.isBlank(detailEntity.getId())){
						continue;
					}
					//如果是提交的话，修改派工详情的日报状态
					if("PRODAILY_END".equals(flagMark)){
						detailEntity.setZd008WorkStatus(BillStatusUtil.PRODISPATDTL_BILL_STATUS_ZONE);
						detailEntity.setZd008WorkDate(new Date());
						detailEntity.setBizVersionMark(detailEntity.getBizVersion());
						detailEntity.setBizVersion(detailEntity.getBizVersion()+1);
						logicProdDispatchingDetailDAO.updateLogicProductionDispatchingDetailDO(detailEntity);
					}
					//保存日报的主表
					LogicProductionDailyDO daily = new LogicProductionDailyDO();
					String id = IDCodeTypeUtil.getId();
					daily.setId(id);
					String formCode = syCodeService.getCode(BillTypeConstant.PRODAILY,BillTypeConstant.PRODAILY,SyCode.DATE_YYMM,5);
					daily.setZd001FormCode(formCode);
					daily.setZd002OriId(detailEntity.getId());
					daily.setZd002OriCode(detailEntity.getZd001FormCode());
					daily.setZd003PiCode(detailEntity.getZd003PiCode());
					daily.setZd004CustomerId(detailEntity.getZd004CustomerId());
					daily.setZd004CustomerName(detailEntity.getZd004CustomerName());
					daily.setZd004CustomerCode(detailEntity.getZd004CustomerCode());
					daily.setZd005OrderDate(detailEntity.getZd005OrderDate());
					daily.setZd006DeliveryDate(detailEntity.getZd006DeliveryDate());
					daily.setZd007SalesMan(detailEntity.getZd007SalesMan());
					daily.setZd008Billstatus(flagMark);
					this.save(daily,SessionUtil.getUser(request));
					//保存日报字表信息
					List<LogicProductionDispatchingDetailItemDO> itemList =(List<LogicProductionDispatchingDetailItemDO>)detailMap.get(detailEntity);
					for (LogicProductionDispatchingDetailItemDO item : itemList) {
						if(item==null||StringUtils.isBlank(item.getId())){
							continue;
						}
						LogicProductionDailyItemDO dailyItem = new LogicProductionDailyItemDO();
						dailyItem.setId(IDCodeTypeUtil.getId());
						dailyItem.setZd001ProDailyId(id);
						dailyItem.setZd002ProDailyCode(formCode);
						dailyItem.setZd003CustomerId(item.getZd003CustomerId());
						dailyItem.setZd004CustomerCode(item.getZd004CustomerCode());
						dailyItem.setZd005CustomerName(item.getZd005CustomerName());
						dailyItem.setZd006MaterialsId(item.getZd006MaterialsId());
						dailyItem.setZd006MaterialsCode(item.getZd006MaterialsCode());
						dailyItem.setZd006MaterialsName(item.getZd006MaterialsName());
						dailyItem.setZd007UseCode(item.getZd007UseCode());
						dailyItem.setZd008UseName(item.getZd008UseName());
						dailyItem.setZd009MaterialsBatch(item.getZd009MaterialsBatch());
						dailyItem.setZd010MaterialsModel(item.getZd010MaterialsModel());
						dailyItem.setZd011MaterialsSpec(item.getZd011MaterialsSpec());
						dailyItem.setZd012MaterialsUnit(item.getZd012MaterialsUnit());
						dailyItem.setZd013Quantity(item.getZd013Quantity());
						dailyItem.setZd014Price(item.getZd014Price());
						dailyItem.setZd015DeliveryDate(item.getZd015DeliveryDate());
						BigDecimal dispQuantity = item.getZd013Quantity()==null?BigDecimal.ZERO:item.getZd013Quantity();
						BigDecimal backQuantity = item.getZd019ReturnQuantity()==null?BigDecimal.ZERO:item.getZd019ReturnQuantity();
						dailyItem.setZd016ProductionQuantity(dispQuantity.subtract(backQuantity));
						dailyItem.setZd017StorageQuantity(item.getZd017StorageQuantity());
						dailyItem.setZd018OutboundQuantity(item.getZd018OutboundQuantity());
						dailyItem.setZd019ReturnQuantity(backQuantity);
						dailyItem.setZd020Remark(item.getZd020Remark());
						dailyItem.setZd021MaterialsDescription(item.getZd021MaterialsDescription());
						dailyItem.setZd022OpenBatch(item.getZd022OpenBatch());
						dailyItem.setZd023MaterialsSize(item.getZd023MaterialsSize());
						dailyItem.setZd024MaterialsPicture(item.getZd024MaterialsPicture());
						dailyItem.setZd025MaterialsAnnex(item.getZd025MaterialsAnnex());
						dailyItem.setZd026MaterialsColor(item.getZd026MaterialsColor());
						dailyItem.setZd027MaterialsQuality(item.getZd027MaterialsQuality());
						dailyItem.setZd028WorkShop(item.getZd028WorkShop());
						dailyItem.setZd028WorkShopName(item.getZd028WorkShopName());
						dailyItem.setZd029Process(item.getZd029Process());
						dailyItem.setZd029ProcessName(item.getZd029ProcessName());
						dailyItem.setZd030DispatQuantity(dispQuantity);
						this.logicProductionDailyItemDAO.insertLogicProductionDailyItemDO(dailyItem);
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()+ e.getMessage());
		}
	}
}
